import React, { useEffect, useState } from 'react';
import {
 Table, Divider, Modal, Form, Input, Select, Switch, Row, Col, Button, TreeSelect, InputNumber, Tooltip, Icon, message,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import MenuTree from '@/components/MenuTree';
import SearchBox from '@/components/SearchBox'
import {
  fetchBtnList,
  deleteBtn,
  saveOrUpdateBtn,
  searchBtn,
} from '@/services/btn';
import {
  fetchMenus,
} from '@/services/menu'
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { confirm } = Modal;
const { Option } = Select;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const columns = [
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '按钮名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '功能描述',
    dataIndex: 'describes',
    key: 'describes',
  },
  {
    title: '关联接口',
    dataIndex: 'url',
    key: 'url',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => <span>{text == 0 ? '启用' : '锁定'}</span>,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
];

const btitle = '1新增，2查询，3修改，4删除，5审核 6.授权 7.修改密码 8.权限配置菜单'
  + '9.权限配置页面元素 10.权限配置功能菜单 11.上传相关功能 12.修改局部 13.局部查询 99.批量启/停用'
  + '98.批量设置分销方案 97.excel导出 96.一键提醒 95.批量导入 94.模板下载 93.批量确认'
  + '92.发送短信 91.发送记录 80.全部商品设置 81.单个商品设置 82.页面跳转'
  + '10000.详情 10001.手动入库'

const ButtonList = props => {
  const { getFieldDecorator } = props.form;
  const { inform } = props.role;
  const [data, setColData] = useState([]);
  const [keys, setKey] = useState(0)
  const [menuList, setMenuList] = useState([])
  const [record, setRecord] = useState([])
  const [btnType, setBtnType] = useState(null)

  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  useEffect(() => {
    getList();
    getMenu()
  }, []);

  // 列表
  const getList = async params => {
    const r = await fetchBtnList(params);
    setColData(r.data);
  };

  // 新增修改
  const handleRole = async params => {
    const r = await saveOrUpdateRole(params);
    if (r.code == 0) getList();
  };

  // 查询
  const searchOneBtn = async params => {
    const r = await searchBtn(params);
    setColData(r.data);
  };

  const removeRole = async record => {
    const res = await deleteBtn({
      id: record.id,
    });
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setColData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  };

  // 菜单列表
  const getMenu = async () => {
    const res = await fetchMenus()
    setMenuList(res.data)
  }

  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      props.dispatch({
        type: 'role/changeModelState',
        payload: {
          inform: record,
        },
      });
    }
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        let params = {}
        btnType == 1
        ? params = {
          ...values,
          id: values.id,
          status: values.status ? 0 : 1,
          menuId: keys[0],
        }
        : params = {
          ...inform,
          ...values,
          id: inform.id ? inform.id : values.id,
          status: values.status ? 0 : 1,
          menuId: keys[0],
        }
        saveOrUpdateBtn(params).then(() => {
          getList()
          setState(!isShow);
        })
      }
    });
  };

  // 查询表单
  const getFields = () => (
      <>
        <Col span={6}>
          <Form.Item label="按钮名称">
            {getFieldDecorator('id', {})(<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
            >
              {data && data.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label="菜单名称">
            {getFieldDecorator('menuId', {})(<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
            >
              {menuList && menuList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label="url">
            {getFieldDecorator('searchUrl', {})(<Input />)}
          </Form.Item>
        </Col>
      </>
    );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      getList({
        ...values,
        url: values.searchUrl,
      });
    });
  };

  // 清空查询条件
  const handleReset = () => {
    props.form.resetFields();
    getList()
  };

  const selectMenu = keys => setKey(keys)

  // 按钮逻辑
  const handleBtn = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一个页面元素！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      case 3:
        return handleStatus(record[0]);
      // 查询
      case 2:
        return handleSearch();
      // 删除
      case 4:
        return removeRole(record[0])
      default:
        break;
    }
  };

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="排序">
            {getFieldDecorator('sort', {
              initialValue: inform && inform.sort,
            })(<InputNumber min={0} />)}
          </Form.Item>
          <Form.Item label="按钮名称">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="type类型">
            {getFieldDecorator('type', {
              initialValue: inform && inform.type,
              rules: [
                {
                  required: true,
                  message: '请输入按钮类型，按钮样式等',
                },
              ],
            })(
            <Input
              suffix={
                <Tooltip title={btitle}>
                  <Icon type="info-circle" style={{ color: 'rgba(255,0,0,.45)' }} />
                </Tooltip>
              }
            />,
            )}
          </Form.Item>
          <Form.Item label="url">
            {getFieldDecorator('url', {
              initialValue: inform && inform.url,
              rules: [
                {
                  required: true,
                  message: '请输入按钮类型，按钮样式等',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="所属菜单">
            {getFieldDecorator('menuId', {
              initialValue: inform && inform.menuId,
            })(<MenuTree
                defaultExpandAll={false}
                checkable={false}
                onSelect={selectMenu}
                defaultSelectedKeys={inform && [String(inform.menuId)]}
              />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('describes', {
              initialValue: inform && inform.describes,
              rules: [
                {
                  required: false,
                  message: '请输入描述',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: !!(inform && !inform.status),
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(ButtonList));
